const express = require('express')
const app = express()
const cors = require('cors')
const joi = require('joi')
const expressJWT = require('express-jwt')

const userRouters = require('./routers/user')
const { ValidationError } = require('joi')
const config = require('./configs/config')

// 注册中间件和路由
// 注册一个处理错误信息的全局中间件
app.use((req, res, next) => {
    res.cc = (err, status=1) => {
        res.send({
            status,
            msg: err
        })
    }

    next()
})
// 注册解析数据的中间件
app.use(express.json())
app.use(express.urlencoded({extended: false}))
// 注册跨域中间件
app.use(cors())
// 注册jwt验证的中间件
app.use(expressJWT({secret: config.secretKey}).unless({path: [/^\/api/]}))
// 注册用户路由
app.use(userRouters)
// 注册捕获异常的全局中间件
app.use((err, req, res, next) => {
    if(err instanceof joi.ValidationError) return res.cc(err)
    if(err.name == 'UnauthorizedError') return res.cc(err.name)

    res.cc(err)
})

app. listen(80, () => {
    console.log('server is running at http://127.0.0.1:80')
})